package com.example.shrio.realm;

import com.example.admin.SysPermission;
import com.example.admin.SysRole;
import com.example.admin.SysUser;
import com.example.shrio.LoginType;
import com.example.shrio.conf.CustomizedToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * 自定义认证、权限（系統用戶）
 *
 * @author wangkai
 * @date: 2019年5月31日 下午1:15:15
 */
public class AdminUserShiroRealm extends AuthorizingRealm {


    /*
     * (non-Javadoc) 认证
     *
     * @see
     * org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.
     * apache.shiro.authc.AuthenticationToken)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取用户的输入的账号.
        CustomizedToken customizedToken = (CustomizedToken) token;
        if(customizedToken.getLoginType().equals(LoginType.ADMIN)){
            return null;
        }
        SysUser userInfo =(SysUser) customizedToken.getUserInfo();
        String password = new String((char[]) token.getCredentials());
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userInfo, // 用户
                password, // 密码
                getName() // realm name
        );
        return authenticationInfo;
    }

    /*
     * (non-Javadoc) 分配权限
     *
     * @see
     * org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache
     * .shiro.subject.PrincipalCollection)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        SysUser userInfo = (SysUser) principals.getPrimaryPrincipal();
        if (userInfo != null && userInfo.getRoleList() != null) {
            for (SysRole role : userInfo.getRoleList()) {
                authorizationInfo.addRole(role.getCode());
                for (SysPermission p : role.getPermissions()) {
                    authorizationInfo.addStringPermission(p.getPermission());
                }
            }
        }
        return authorizationInfo;
    }

}
